package com.ekuaitu.kuaitustaff.activity;


import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.ReplacementTransformationMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ekuaitu.kuaitustaff.BuildConfig;
import com.ekuaitu.kuaitustaff.R;
import com.ekuaitu.kuaitustaff.adapter.BottomDialogAdapter;
import com.ekuaitu.kuaitustaff.adapter.CarPopTypeAdapter;
import com.ekuaitu.kuaitustaff.adapter.GridViewAddImgesAdpter;
import com.ekuaitu.kuaitustaff.api.ApiService;
import com.ekuaitu.kuaitustaff.api.ApiStore;
import com.ekuaitu.kuaitustaff.api.UrlConstant;
import com.ekuaitu.kuaitustaff.application.MyApplication;
import com.ekuaitu.kuaitustaff.baiduMap.LocationFilter;
import com.ekuaitu.kuaitustaff.base.BaseActivity;
import com.ekuaitu.kuaitustaff.bean.CarTaskfinishBean;
import com.ekuaitu.kuaitustaff.bean.CompleteBean;
import com.ekuaitu.kuaitustaff.bean.ResultBean;
import com.ekuaitu.kuaitustaff.bean.ReturnCarCommentBean;
import com.ekuaitu.kuaitustaff.bean.ReturnCarPositionOptionsBean;
import com.ekuaitu.kuaitustaff.bean.UploadImageBaidu;
import com.ekuaitu.kuaitustaff.utils.AntiShake;
import com.ekuaitu.kuaitustaff.utils.AppManager;
import com.ekuaitu.kuaitustaff.utils.CheckRegexUtils;
import com.ekuaitu.kuaitustaff.utils.Constants;
import com.ekuaitu.kuaitustaff.utils.Dialogs.DialogOneButton;
import com.ekuaitu.kuaitustaff.utils.Dialogs.DialogTwoButton;
import com.ekuaitu.kuaitustaff.utils.ImageLoader;
import com.ekuaitu.kuaitustaff.utils.IntentKey;
import com.ekuaitu.kuaitustaff.utils.IntentUtil;
import com.ekuaitu.kuaitustaff.utils.Logger;
import com.ekuaitu.kuaitustaff.utils.SDCardUtils;
import com.ekuaitu.kuaitustaff.utils.SPKey;
import com.ekuaitu.kuaitustaff.utils.SPUtils;
import com.ekuaitu.kuaitustaff.utils.ToastUtils;
import com.ekuaitu.kuaitustaff.utils.UploadPicUtil;
import com.ekuaitu.kuaitustaff.utils.ble.BleConstants;
import com.ekuaitu.kuaitustaff.utils.ble.BluetoothHelper;
import com.ekuaitu.kuaitustaff.widget.NoScrollGridView;
import com.ekuaitu.kuaitustaff.widget.WheelView;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.baidu.location.BDLocation.TypeNetWorkLocation;
import static com.baidu.location.BDLocation.TypeServerError;
import static com.ekuaitu.kuaitustaff.utils.Constants.PERMISSION_REQUEST_CODE;
import static com.ekuaitu.kuaitustaff.utils.ble.BluetoothHelper.REQUEST_OPEN_BLE_ONCE;


public class CarTaskActivity extends BaseActivity {


    @BindView(R.id.linear_beizhu)
    LinearLayout linear_beizhu;
    @BindView(R.id.edt_beizhu)
    EditText edt_beizhu;
    @BindView(R.id.tv_sure)
    TextView tv_sure;
    @BindView(R.id.tv_state)
    TextView tv_state;
    @BindView(R.id.rl_select)
    RelativeLayout rl_select;
    @BindView(R.id.rl_shifttype)
    RelativeLayout rl_shifttype;
    @BindView(R.id.tv_shifttype)
    TextView tv_shifttype;
    @BindView(R.id.radio_button_free)
    RadioButton radioButtonFree;
    @BindView(R.id.radion_button_charge)
    RadioButton radionButtonCharge;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;

    private Context mContext = this;
    private String orderId, carId, shortName, licenseTag;
    private CarPopTypeAdapter typeAdapter;
    private List<CarTaskfinishBean.AttachmentBean.TaskListBean> taskListBean;
    private String locationName, isOperate, frontSeat, backSeat, frontLeft, backRight, taskTypeId;

    private TextView pop_tv_cancel;
    private TextView pop_tv_finish;
    private WheelView pop_wheelview_type;
    private PopupWindow popwindow_selecttype;
    private View popwindow_select_type;
    private int position;
    private View layout_view;


    private int submitType;
    private File compressFile;
    private String[] picKeyArray = new String[]{"", "", "", ""};
    private boolean flag, flag1, flag2, flag3, flag4, typeFlag;
    private Uri imageUri;
    private CarTaskfinishBean.AttachmentBean attachmentBean;

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.iv_leftfront)
    ImageView iv_leftfront;
    @BindView(R.id.iv_rightback)
    ImageView iv_rightback;
    @BindView(R.id.iv_front)
    ImageView iv_front;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.linear_takephoto)
    LinearLayout linear_takephoto;
    //还车备注
    @BindView(R.id.choose_type)
    RelativeLayout choose_type;
    @BindView(R.id.choose_type_tv)
    TextView choose_type_tv;
    @BindView(R.id.return_car_out_gv)
    NoScrollGridView returnCarOutGv;
    @BindView(R.id.return_car_in_park_name)
    EditText returnCarInParkName;
    @BindView(R.id.return_car_in_park_num)
    EditText returnCarInParkNum;
    @BindView(R.id.return_car_in_park_ground)
    TextView return_car_in_park_ground;
    @BindView(R.id.return_car_in)
    LinearLayout returnCarIn;
    @BindView(R.id.tv_title_2)
    TextView tv_title_2;
    private ArrayList<String> datas;
    private GridViewAddImgesAdpter gridViewAddImgesAdpter;
    private BleConstants.OperateType operateType;
    private String onGround = "";
    private BottomDialogAdapter spinerAdapter;
    private String remarkMsg;
    private String remarkMsgUp;
    private String key, imgs;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case 1:
                    showLoadingDialog();
                    break;
                case 2:
                    dismissLoadingDialog();
                    //成功压缩
                    Logger.d("returnCar", "压缩成功" + compressFile.getName());
                    //上传图片
                    uploadImage(compressFile);
                    if (submitType == 0) {
                        ImageLoader.getInstance().displayImage(mContext, compressFile, iv_leftfront);
                        flag1 = true;
                    } else if (submitType == 1) {
                        ImageLoader.getInstance().displayImage(mContext, compressFile, iv_rightback);
                        flag2 = true;
                    } else if (submitType == 2) {
                        ImageLoader.getInstance().displayImage(mContext, compressFile, iv_front);
                        flag3 = true;
                    } else {
                        ImageLoader.getInstance().displayImage(mContext, compressFile, iv_back);
                        flag4 = true;
                    }
                    if (flag1 && flag2 && flag3 && flag4) {
                        flag = true;
                        checkButtonColor();
                    }
                    break;
                case 3:
                    //压缩失败
                    dismissLoadingDialog();
                    Logger.d("returnCar", "压缩失败" + compressFile.getName());
                    break;
                case 4: //上传成功
                    Logger.d("returnCar", "上传成功" + compressFile.getName());
                    SPUtils.getInstance(mContext).putStringValue(SPKey.RETURN_CAR_PIC_NAME, SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_NAME) + "," + compressFile.getName());
                    Logger.d("returnCar", "上传成功总共" + SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_NAME));
                    break;
                case 5:
                    //上传失败
                    Logger.d("returnCar", "上传失败" + compressFile.getName());
                    break;
                case 6:
                    //上传取消
                    Logger.d("returnCar", "上传取消" + compressFile.getName());
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private File outputImage;
    private LocationClient mLocClient;
    private boolean isReceiveLoc = false;
    private CarTaskLocationListener myListener = new CarTaskLocationListener();
    private File fileDir;

    @Override
    protected int getLayoutId() {
        layout_view = View.inflate(mContext, R.layout.activity_car_task, null);
        return R.layout.activity_car_task;
    }

    @Override
    protected void initView() {
        tv_sure.setClickable(false);
        initSelectTypePopWindowView();

        //还车备注
        returnCarInParkNum.setTransformationMethod(new ReplacementTransformationMethod() {
            @Override
            protected char[] getOriginal() {
                char[] originalCharArr = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
                return originalCharArr;
            }

            @Override
            protected char[] getReplacement() {
                char[] replacementCharArr = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
                return replacementCharArr;
            }
        });

        returnCarInParkNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(returnCarInParkNum.getText().toString()))
                    SPUtils.getInstance(mContext).putStringValue(SPKey.RETURN_CAR_PARKNUM, returnCarInParkNum.getText().toString() + "");
            }
        });
        //indoor
        returnCarInParkName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, SearchParkActivity.class);
                intent.putExtra("content", returnCarInParkName.getText().toString());
                startActivity(intent);
            }
        });
        //outDoor 初始化
        SPUtils.getInstance(mContext).removeValue(SPKey.RETURN_CAR_PIC_NAME);
        fileDir = new File(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + "returncar");
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        File[] files = fileDir.listFiles();
        if (files != null) {
            Arrays.sort(files);
            for (int i = 0; i < files.length; i++) {
                if (files[i].getName().endsWith("jpg")) {
                    files[i].delete();
                }
            }
        }
        datas = new ArrayList<>();
        gridViewAddImgesAdpter = new GridViewAddImgesAdpter(datas, mContext);
        returnCarOutGv.setAdapter(gridViewAddImgesAdpter);
        returnCarOutGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (datas == null || datas.size() == position) {
                    checkperssionAndCamera(1);
                } else {
                    Logger.d("returnCarrename4", "click--" + position);
                    Intent intent = new Intent(mContext, PhotoViewActivity.class);
                    intent.putStringArrayListExtra("pictures", datas);
                    intent.putExtra("pictureType", 1);
                    intent.putExtra("toIndex", position);
                    int location[] = new int[2];
                    view.getLocationOnScreen(location);
                    intent.putExtra("left", location[0]);
                    intent.putExtra("top", location[1]);
                    intent.putExtra("height", view.getHeight());
                    intent.putExtra("width", view.getWidth());
                    mContext.startActivity(intent);
                    //((CarTaskActivity) mContext).overridePendingTransition(0, 0);
                }
            }
        });
    }

    @Override
    protected void initData() {

        orderId = getIntent().getStringExtra(IntentKey.INTENT_ORDER_ID);
        carId = getIntent().getStringExtra(IntentKey.INTENT_CAR_ID);
        shortName = getIntent().getStringExtra(IntentKey.INTENT_TASKTYPE);
        licenseTag = getIntent().getStringExtra(IntentKey.INTENT_LICENSETAG);
        isOperate = getIntent().getStringExtra(IntentKey.INTENT_ISOPERATE);
        locationName = getIntent().getStringExtra(IntentKey.INTENT_LOCATIONNAME);

        //2不可运营  1 可运营
        if ("2".equals(isOperate)) {
            confirm();
        }
        if (!TextUtils.isEmpty(locationName)) {
            edt_beizhu.setText(locationName);
            remarkMsgUp = locationName;
        } else {
            edt_beizhu.setText("点击图片查看车辆位置");
            remarkMsgUp = "点击图片查看车辆位置";
        }
        rl_shifttype.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                }
                popwindow_selecttype.showAtLocation(layout_view, Gravity.BOTTOM, 0, 0);
                backgroundAlpha(0.7f);
            }
        });
    }

    private void getPermission() {
        //获取动态权限
        isReceiveLoc = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionLists = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (!permissionLists.isEmpty()) {//有拒绝的权限
                ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), PERMISSION_REQUEST_CODE);
            } else {
                startLocation();
            }
        } else {
            startLocation();
        }
    }

    private void startLocation() {
        showLoadingDialog();
        mLocClient = new LocationClient(this);
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        option.setIsNeedLocationDescribe(true);
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(0);
        mLocClient.setLocOption(option);
        mLocClient.registerLocationListener(myListener);
        if (mLocClient != null) {
            mLocClient.start();
        }
    }

    // 初始化popwindow
    private void initSelectTypePopWindowView() {

        popwindow_select_type = View.inflate(mContext, R.layout.pop_select, null);
        pop_tv_cancel = (TextView) popwindow_select_type.findViewById(R.id.pop_tv_cancel);
        pop_tv_finish = (TextView) popwindow_select_type.findViewById(R.id.pop_tv_finish);
        pop_wheelview_type = (WheelView) popwindow_select_type.findViewById(R.id.wheel1);

        popwindow_selecttype = new PopupWindow(popwindow_select_type, LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        popwindow_selecttype.setAnimationStyle(R.style.popwindow_in_out);
        popwindow_selecttype.setBackgroundDrawable(getResources().getDrawable(
                R.color.colorPrimary));// 设置弹出窗口的背景
        // 点击空白处时，隐藏掉pop窗口
        popwindow_selecttype.setFocusable(true);
        popwindow_selecttype.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
        pop_tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popwindow_selecttype.dismiss();
            }
        });
        pop_tv_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (taskListBean != null && taskListBean.size() != 0) {
                    position = pop_wheelview_type.getSelectedItemPosition();
                    tv_shifttype.setText(taskListBean.get(position).getInstruction());
                    taskTypeId = taskListBean.get(position).getTaskType();

                    typeFlag = true;
                    popwindow_selecttype.dismiss();
                    checkButtonColor();
                }
            }
        });

    }

    //网点列表接口
    private void confirm() {
        showLoadingDialog();
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).confirm(MyApplication.getInstance().getRequestFieldMap(), orderId, carId)
                .enqueue(new Callback<CarTaskfinishBean>() {
                    @Override
                    public void onResponse(Call<CarTaskfinishBean> call, Response<CarTaskfinishBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getErrCode() == 0) {
                                dismissLoadingDialog();
                                if (response.body().getAttachment() != null) {
                                    try {
                                        attachmentBean = response.body().getAttachment();
                                        //洗车工单（不可运营）只拍照，之前的照片不用带出，无类型选择
                                        if (!"19".equals(shortName)) {
                                            tv_title.setText("确认转移任务");
                                            tv_title_2.setText("请仔细填写转移原因");
                                            rl_shifttype.setVisibility(View.VISIBLE);
                                            taskListBean = attachmentBean.getTaskList();
                                            frontSeat = attachmentBean.getCarPicture().getFrontSeat();
                                            backSeat = attachmentBean.getCarPicture().getBackSeat();
                                            frontLeft = attachmentBean.getCarPicture().getFrontLeft();
                                            backRight = attachmentBean.getCarPicture().getBackRight();
                                            loadPhoto();
                                            typeAdapter = new CarPopTypeAdapter(mContext, taskListBean, "", true);
                                            pop_wheelview_type.setAdapter(typeAdapter);
                                        } else {
                                            tv_title.setText("确认完成任务");
                                            tv_title_2.setText("请对车辆状况进行拍照");
                                            rl_shifttype.setVisibility(View.GONE);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            } else if (response.body().getErrCode() == 11) {
                                dismissLoadingDialog();
                                ToastUtils.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                                IntentUtil.toLoginActivity(mContext);
                                AppManager.getAppManager().finishAllActivity();
                            } else {
                                dismissLoadingDialog();
                                ToastUtils.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<CarTaskfinishBean> call, Throwable t) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    //关单
    private void closeWorkOrder(String bleResult) {
        showLoadingDialog();
        JSONObject bodyJson = new JSONObject();
        try {
            bodyJson = new JSONObject(new Gson().toJson(((MyApplication) getApplication()).getRequestFieldMap()));
            bodyJson.put("car_id", carId);
            bodyJson.put("staff_id", orderId);
            JSONObject commentJson = new JSONObject();
            commentJson.put("onGround", onGround);
            if (imgs != null) {
                commentJson.put("imgs", imgs);
            }
            commentJson.put("remarkMsg", remarkMsg == null ? "" : remarkMsg.toUpperCase());
            commentJson.put("orderId", orderId);
            commentJson.put("free_parking", radioButtonFree.isChecked() ? "2" : "1");
            bodyJson.put("comment", commentJson);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).returnCarComment(body).enqueue(new Callback<ReturnCarCommentBean>() {
            @Override
            public void onResponse(Call<ReturnCarCommentBean> call, Response<ReturnCarCommentBean> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getMsg_code() == 200) {
                    //关单上线在提交还车备注成功之后
                    HashMap<String, String> eventMap = new HashMap<>();
                    eventMap.put("action", "关单上线");
                    eventMap.put("comment", "关单上线");
                    eventMap.put("car", licenseTag);
                    eventMap.put("order", orderId);
                    new ApiStore().getApiService(UrlConstant.Request.BASE_URL_NEW, "v/staff-order/closeWorkOrder", eventMap, new ApiStore.ParseCallBack() {

                        @Override
                        public void onSaveFailure(String error) {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, error, ToastUtils.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onSaveSuccess(ApiService apiService) {
                            try {
                                apiService.closeOrder(MyApplication.getInstance().getRequestFieldMap(),
                                        "1", orderId, carId, edt_beizhu.getText().toString(), picKeyArray[0], picKeyArray[1], picKeyArray[2], picKeyArray[3], taskTypeId, bleResult)
                                        .enqueue(new Callback<ResultBean>() {
                                            @Override
                                            public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                                                if (response.isSuccessful() && response.body() != null) {
                                                    dismissLoadingDialog();
                                                    if (response.body().getErrCode() == 0) {
                                                        ToastUtils.makeText(mContext, response.body().getMessage(), 0, ToastUtils.LENGTH_LONG).show();
                                                        //通知主页更新界面
                                                        EventBus.getDefault().post(new CompleteBean());
                                                        //清除照片
                                                        SPUtils.getInstance(mContext).removeValue(SPKey.RETURN_CAR_PIC_NAME);
                                                        File[] files = fileDir.listFiles();
                                                        if (files != null) {
                                                            Arrays.sort(files);
                                                            for (int i = 0; i < files.length; i++) {
                                                                if (files[i].getName().endsWith("jpg")) {
                                                                    files[i].delete();
                                                                }
                                                            }
                                                        }
                                                        //清除cache
                                                        SPUtils.getInstance(mContext).removeValue(SPKey.RETURN_CAR_SPINNER_NAME);
                                                        SPUtils.getInstance(mContext).removeValue(SPKey.RETURN_CAR_PARKNAME);
                                                        SPUtils.getInstance(mContext).removeValue(SPKey.RETURN_CAR_PARKNUM);
                                                        SPUtils.getInstance(mContext).removeValue(SPKey.RETURN_CAR_POSITION);
                                                        //跳转任务完成界面
                                                        IntentUtil.toCarFinishTaskActivity(mContext, orderId, carId, licenseTag);
                                                        AppManager.getAppManager().finishActivity();
                                                    } else if (response.body().getErrCode() == 11) {
                                                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_LONG).show();
                                                        IntentUtil.toLoginActivity(mContext);
                                                        AppManager.getAppManager().finishAllActivity();

                                                    } else if (response.body().getErrCode() == 1001) {
                                                        showOneButtonDialog("", "提醒", response.body().getMessage(), "确定");

                                                    } else {
                                                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_LONG).show();
                                                    }
                                                } else {
                                                    dismissLoadingDialog();
                                                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                                                }
                                            }

                                            @Override
                                            public void onFailure(Call<ResultBean> call, Throwable t) {
                                                dismissLoadingDialog();
                                                Log.i("neterror", "关单" + t.toString());
                                                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                                            }
                                        });
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ReturnCarCommentBean> call, Throwable t) {
                Logger.i("return car", t.getMessage());
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });

    }

    private void loadPhoto() {
        if (!"0".equals(frontLeft) && frontLeft != null) {
            ImageLoader.getInstance().displayImage(getApplicationContext(),
                    MyApplication.imageUrl + frontLeft, iv_leftfront);
            flag1 = true;
            submitType = 0;
            picKeyArray[submitType] = frontLeft;

        }
        if (!"0".equals(backRight) && backRight != null) {

            ImageLoader.getInstance().displayImage(getApplicationContext(),
                    MyApplication.imageUrl + backRight, iv_rightback);
            flag2 = true;
            submitType = 1;
            picKeyArray[submitType] = backRight;

        }
        if (!"0".equals(frontSeat) && frontSeat != null) {

            ImageLoader.getInstance().displayImage(getApplicationContext(),
                    MyApplication.imageUrl + frontSeat, iv_front);
            flag3 = true;
            submitType = 2;
            picKeyArray[submitType] = frontSeat;

        }
        if (!"0".equals(backSeat) && backSeat != null) {

            ImageLoader.getInstance().displayImage(getApplicationContext(),
                    MyApplication.imageUrl + backSeat, iv_back);
            flag4 = true;
            submitType = 3;
            picKeyArray[submitType] = backSeat;

        }
        if (flag1 && flag2 && flag3 && flag4) {
            flag = true;
        }
    }

    private void checkButtonColor() {
        //2不可运营  1 可运营
        if ("2".equals(isOperate)) {
            if (("19".equals(shortName) && flag) || (typeFlag && flag)) {//不可运营得需要校验选择类型
                tv_sure.setBackgroundResource(R.drawable.btn_bg);
                tv_sure.setClickable(true);
            } else {
                tv_sure.setBackgroundResource(R.drawable.btn_gray_bg);
                tv_sure.setClickable(false);
            }
        } else {
            if (flag) {
                tv_sure.setBackgroundResource(R.drawable.btn_bg);
                tv_sure.setClickable(true);
            } else {
                tv_sure.setBackgroundResource(R.drawable.btn_gray_bg);
                tv_sure.setClickable(false);
            }
        }
    }


    @OnClick({R.id.choose_type, R.id.tv_sure, R.id.title_back, R.id.iv_leftfront, R.id.iv_rightback, R.id.iv_front, R.id.iv_back})
    public void onClick(View view) {
        if (AntiShake.check(view.getId())) return; //判断是否多次点击
        switch (view.getId()) {
            case R.id.title_back:
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.iv_leftfront:
                submitType = 0;
                checkperssionAndCamera(0);
                break;
            case R.id.iv_rightback:
                submitType = 1;
                checkperssionAndCamera(0);
                break;
            case R.id.iv_front:
                submitType = 2;
                checkperssionAndCamera(0);
                break;
            case R.id.iv_back:
                submitType = 3;
                checkperssionAndCamera(0);
                break;
            case R.id.tv_sure:
                getPermission();
                break;
            case R.id.choose_type:
                showBottomSheetDialog();
                break;

        }
    }

    private void dropOffCar() {
        operateType = BleConstants.OperateType.CLOSE_DOOR_POWER;
        if (BluetoothHelper.getInstance().isCarSupportBle(mContext)) {
            showLoadingDialog();
            //蓝牙开，未连接
            if (BluetoothHelper.getInstance().isBluetoothOpened() && !BluetoothHelper.getInstance().isConnect()) {
                BluetoothHelper.getInstance().searchDevice(false, "关门断电", 1, bothSearchResponse);
            }
            //蓝牙开，已连接  蓝牙网络同时发送关门指令
            if (BluetoothHelper.getInstance().isBluetoothOpened() && BluetoothHelper.getInstance().isConnect()) {
                BluetoothHelper.getInstance().operateCar(true, "关门断电", operateType, onOperateCarListener);
            }
            //蓝牙未开
            else if (!BluetoothHelper.getInstance().isBluetoothOpened()) {
                BluetoothHelper.getInstance().openBluetooth(CarTaskActivity.this, REQUEST_OPEN_BLE_ONCE);
            }
        } else {
            closeWorkOrder(null);
            BluetoothHelper.getInstance().getBleInfo(carId, orderId, licenseTag, mContext, null);
        }
    }

    private void showBottomSheetDialog() {
        BottomSheetDialog dialog = new BottomSheetDialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_dialog, null);
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        handleList(view, dialog);
        dialog.show();
    }

    private void handleList(View contentView, BottomSheetDialog dialog) {
        List<ReturnCarPositionOptionsBean> returnCarPositionOptionsBeanList = new ArrayList<>();
        ReturnCarPositionOptionsBean returnCarPositionOptionsBean = new ReturnCarPositionOptionsBean();
        returnCarPositionOptionsBean.setName("地面");
        returnCarPositionOptionsBean.setType("pic");
        returnCarPositionOptionsBeanList.add(returnCarPositionOptionsBean);
        ReturnCarPositionOptionsBean returnCarPositionOptionsBean1 = new ReturnCarPositionOptionsBean();
        returnCarPositionOptionsBean1.setName("地下一层");
        returnCarPositionOptionsBean1.setType("poi");
        returnCarPositionOptionsBeanList.add(returnCarPositionOptionsBean1);
        ReturnCarPositionOptionsBean returnCarPositionOptionsBean2 = new ReturnCarPositionOptionsBean();
        returnCarPositionOptionsBean2.setName("地下二层");
        returnCarPositionOptionsBean2.setType("poi");
        returnCarPositionOptionsBeanList.add(returnCarPositionOptionsBean2);
        ReturnCarPositionOptionsBean returnCarPositionOptionsBean3 = new ReturnCarPositionOptionsBean();
        returnCarPositionOptionsBean3.setName("地下三层");
        returnCarPositionOptionsBean3.setType("poi");
        returnCarPositionOptionsBeanList.add(returnCarPositionOptionsBean3);
        ReturnCarPositionOptionsBean returnCarPositionOptionsBean4 = new ReturnCarPositionOptionsBean();
        returnCarPositionOptionsBean4.setName("地下四层");
        returnCarPositionOptionsBean4.setType("poi");
        returnCarPositionOptionsBeanList.add(returnCarPositionOptionsBean4);
        ReturnCarPositionOptionsBean returnCarPositionOptionsBean5 = new ReturnCarPositionOptionsBean();
        returnCarPositionOptionsBean5.setName("地下五层");
        returnCarPositionOptionsBean5.setType("poi");
        returnCarPositionOptionsBeanList.add(returnCarPositionOptionsBean5);
        ReturnCarPositionOptionsBean returnCarPositionOptionsBean6 = new ReturnCarPositionOptionsBean();
        returnCarPositionOptionsBean6.setName("地下六层");
        returnCarPositionOptionsBean6.setType("poi");
        returnCarPositionOptionsBeanList.add(returnCarPositionOptionsBean6);
        ReturnCarPositionOptionsBean returnCarPositionOptionsBean7 = new ReturnCarPositionOptionsBean();
        returnCarPositionOptionsBean7.setName("地下七层");
        returnCarPositionOptionsBean7.setType("poi");
        returnCarPositionOptionsBeanList.add(returnCarPositionOptionsBean7);
        RecyclerView recyclerView = (RecyclerView) contentView.findViewById(R.id.recyclerView);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        spinerAdapter = new BottomDialogAdapter(returnCarPositionOptionsBeanList);
        recyclerView.setAdapter(spinerAdapter);
        spinerAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SPUtils.getInstance(mContext).putStringValue(SPKey.RETURN_CAR_SPINNER_NAME, returnCarPositionOptionsBeanList.get(position).getName());//缓存
                choose_type_tv.setText(returnCarPositionOptionsBeanList.get(position).getName());
                return_car_in_park_ground.setText(returnCarPositionOptionsBeanList.get(position).getName());
                if (returnCarPositionOptionsBeanList.get(position).getType().equals("poi")) {
                    returnCarIn.setVisibility(View.VISIBLE);
                    returnCarOutGv.setVisibility(View.GONE);
                    onGround = "0";
                } else if (returnCarPositionOptionsBeanList.get(position).getType().equals("pic")) {
                    returnCarIn.setVisibility(View.GONE);
                    returnCarOutGv.setVisibility(View.VISIBLE);
                    onGround = "1";
                    if (datas == null || datas.size() < 6) {
                        checkperssionAndCamera(1);
                    }
                }
                SPUtils.getInstance(mContext).putStringValue(SPKey.RETURN_CAR_POSITION, onGround);
                dialog.dismiss();
            }
        });
        spinerAdapter.notifyDataSetChanged();
    }

    public void checkperssionAndCamera(int type) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionLists = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.CAMERA);
            }
            if (!permissionLists.isEmpty()) {//有拒绝的权限
                ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), Constants.PERMISSION_REQUEST_CAMERA);
            } else {
                if (type == 0) {
                    takePhoto();
                } else {
                    takePhotoCustom();
                }
            }
        } else {
            if (type == 0) {
                takePhoto();
            } else {
                takePhotoCustom();
            }
        }

    }

    private void takePhotoCustom() {
        Intent intent = new Intent(mContext, ReturnCarCameraActivity.class);
        intent.putExtra("orderId", orderId);
        startActivity(intent);
    }

    private void takePhoto() {
        // 创建File对象，用于存储拍照后的图片
        outputImage = new File(getExternalCacheDir(), "output_image.jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT < 24) {
            imageUri = Uri.fromFile(outputImage);
        } else {
            imageUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", outputImage);
        }
        // 启动相机程序
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, submitType);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //indoor
        if (intent.getStringExtra("searchParkName") != null) {
            returnCarInParkName.setText(intent.getStringExtra("searchParkName"));
            SPUtils.getInstance(mContext).putStringValue(SPKey.RETURN_CAR_PARKNAME, returnCarInParkName.getText().toString() + "");
        }
        //outdoor
        datas = new ArrayList<>();
        File[] files = fileDir.listFiles();
        if (files != null) {
            Arrays.sort(files);
            for (int i = 0; i < files.length; i++) {
                if (files[i].getName().endsWith("jpg") && files[i].getName().startsWith(orderId)) {
                    Logger.d("returnCarrename3OnNewIntent", files[i].getAbsolutePath());
                    datas.add(files[i].getAbsolutePath());
                }
            }
        }
        gridViewAddImgesAdpter.notifyDataSetChanged(datas);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("imageUrl", MyApplication.imageUrl);
        outState.putString("orderId", orderId);
        outState.putString("carId", carId);
        outState.putString("shortName", shortName);
        outState.putString("licenseTag", licenseTag);
        outState.putString("isOperate", isOperate);
        outState.putString("locationName", locationName);
        outState.putStringArray("picKeyArray", picKeyArray);
        outState.putBoolean("flag", flag);
        outState.putBoolean("flag1", flag1);
        outState.putBoolean("flag2", flag2);
        outState.putBoolean("flag3", flag3);
        outState.putBoolean("flag4", flag4);
        outState.putInt("submitType", submitType);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Logger.i("onrestore", MyApplication.imageUrl);
        outputImage = new File(getExternalCacheDir(), "output_image.jpg");
        MyApplication.imageUrl = savedInstanceState.getString("imageUrl");
        orderId = savedInstanceState.getString("orderId");
        carId = savedInstanceState.getString("carId");
        shortName = savedInstanceState.getString("shortName");
        licenseTag = savedInstanceState.getString("licenseTag");
        isOperate = savedInstanceState.getString("isOperate");
        locationName = savedInstanceState.getString("locationName");
        //2不可运营  1 可运营
        if ("2".equals(isOperate)) {
            confirm();
        }
        if (!TextUtils.isEmpty(locationName)) {
            edt_beizhu.setText(locationName);
            remarkMsgUp = locationName;
        } else {
            edt_beizhu.setText("点击图片查看车辆位置");
            remarkMsgUp = "点击图片查看车辆位置";
        }
        picKeyArray = savedInstanceState.getStringArray("picKeyArray");
        flag = savedInstanceState.getBoolean("flag");
        flag1 = savedInstanceState.getBoolean("flag1");
        flag2 = savedInstanceState.getBoolean("flag2");
        flag3 = savedInstanceState.getBoolean("flag3");
        flag4 = savedInstanceState.getBoolean("flag4");
        submitType = savedInstanceState.getInt("submitType");
        if (!TextUtils.isEmpty(picKeyArray[0])) {
            ImageLoader.getInstance().displayImage(getApplicationContext(),
                    MyApplication.imageUrl + picKeyArray[0], iv_leftfront);
        }
        if (!TextUtils.isEmpty(picKeyArray[1])) {
            ImageLoader.getInstance().displayImage(getApplicationContext(),
                    MyApplication.imageUrl + picKeyArray[1], iv_rightback);
        }
        if (!TextUtils.isEmpty(picKeyArray[2])) {
            ImageLoader.getInstance().displayImage(getApplicationContext(),
                    MyApplication.imageUrl + picKeyArray[2], iv_front);
        }
        if (!TextUtils.isEmpty(picKeyArray[3])) {
            ImageLoader.getInstance().displayImage(getApplicationContext(),
                    MyApplication.imageUrl + picKeyArray[3], iv_back);
        }
        checkButtonColor();
        //fix null point bug
        edt_beizhu = findViewById(R.id.edt_beizhu);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != RESULT_OK && requestCode == REQUEST_OPEN_BLE_ONCE) {
            dismissLoadingDialog();
        } else if (resultCode == RESULT_OK && requestCode == REQUEST_OPEN_BLE_ONCE) {
            showLoadingDialog();
            BluetoothHelper.getInstance().searchDevice(false, "关门断电", 1, bothSearchResponse);
        } else if (resultCode == RESULT_OK && requestCode == submitType) {   //获得图片后
            try {
                Luban.with(mContext)
                        .load(outputImage)  //传入要压缩的图片
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                Message message = new Message();
                                message.arg1 = 1;
                                handler.sendMessage(message);
                            }

                            @Override
                            public void onSuccess(File file) {
                                Message message = new Message();
                                message.arg1 = 2;
                                Logger.i("returnCar-rename1", file.getAbsolutePath());
                                File[] files = fileDir.listFiles();
                                if (files != null) {
                                    Arrays.sort(files);
                                    for (int i = 0; i < files.length; i++) {
                                        if (files[i].getName().endsWith("jpg") && files[i].getName().startsWith(submitType + "-" + orderId + "-")) {
                                            files[i].delete();//有了就删除，只保留submitType对应的一张
                                        }
                                    }
                                }
                                compressFile = new File(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + "returncar" + File.separator + submitType + "-" + orderId + "-" + SDCardUtils.createReturnCarFileName(MyApplication.getInstance().getUserId()) + ".jpg");
                                file.renameTo(compressFile);
                                picKeyArray[submitType] = getFileNameNoExOrder(compressFile);
                                Logger.i("returnCar-rename2", compressFile.getAbsolutePath());
                                handler.sendMessage(message);
                            }

                            @Override
                            public void onError(Throwable e) {
                                Message message = new Message();
                                message.arg1 = 3;
                                handler.sendMessage(message);
                            }
                        }).launch();    //启动压缩
            } catch (Exception e) {
                Message message = new Message();
                message.arg1 = 3;
                handler.sendMessage(message);
                e.printStackTrace();
            }
        }
    }

    /*
     * Java文件操作 获取不带扩展名的文件名
     */
    public String getFileNameNoExOrder(File nameFile) {
        String filename = nameFile.getName();
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                int index = filename.lastIndexOf("-");
                return filename.substring(index + 1, dot);
            }
        }
        return filename;
    }

    private void uploadImage(final File picFile) {
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).uploadImageBaidu(((MyApplication) getApplication()).getRequestFieldMap(), "stsToken", "upload").enqueue(new Callback<UploadImageBaidu>() {
            @Override
            public void onResponse(Call<UploadImageBaidu> call, Response<UploadImageBaidu> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getErrCode() == 0) {
                        key = getFileNameNoExOrder(picFile);
                        Logger.i("returnCar-nameFile", picFile.toString());
                        Logger.i("returnCar-name", key + "");
                        UploadPicUtil.getInstance().uploadPicToBos(picFile, response.body().getAttachment().getAk(),
                                response.body().getAttachment().getSk(), response.body().getAttachment().getBucketName(),
                                response.body().getAttachment().getStsToken(),
                                response.body().getAttachment().getBucketName(),
                                key, new UploadPicUtil.OnFinishListener() {
                                    @Override
                                    public void onSuccess() {
                                        Message message = new Message();
                                        message.arg1 = 4;
                                        Bundle b = new Bundle();
                                        message.setData(b);
                                        handler.sendMessage(message);
                                    }

                                    @Override
                                    public void onFailure(String failReason) {
                                        Message message = new Message();
                                        message.arg1 = 5;
                                        Bundle b = new Bundle();
                                        b.putString("failReason", failReason);
                                        message.setData(b);
                                        handler.sendMessage(message);
                                    }
                                });

                    } else {
                        Message message = new Message();
                        message.arg1 = 5;
                        handler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.arg1 = 5;
                    handler.sendMessage(message);
                }
            }

            @Override
            public void onFailure(Call<UploadImageBaidu> call, Throwable t) {
                Message message = new Message();
                message.arg1 = 5;
                handler.sendMessage(message);
            }
        });
    }

    BluetoothHelper.BothSearchResponse bothSearchResponse = new BluetoothHelper.BothSearchResponse() {
        @Override
        public void onSearchSuccess(String mac, String bleName) {
            Logger.i("bleinfo", "onSearchSuccess");
            BluetoothHelper.getInstance().connectDevice(connectResponse, 1);
        }

        @Override
        public void onSearchTimeout() {
            dismissLoadingDialog();
            Logger.i("bleinfo", "扫描超时,关单");
            closeWorkOrder("2");
            ApiStore.bleRecord("2", orderId, carId, "connect");
        }

        @Override
        public void onSearchTimeoutEveryTime() {

        }
    };

    /**
     * 蓝牙连接的结果
     */
    BluetoothHelper.BothConnectResponse connectResponse = new BluetoothHelper.BothConnectResponse() {
        @Override
        public void onConnectSuccess() {
            Logger.i("bleinfo", "连接上了");
            // 连接上立即发送数据会失败
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (operateType == BleConstants.OperateType.CLOSE_DOOR_POWER) {
                        BluetoothHelper.getInstance().operateCar(false, "关门断电", operateType, onOperateCarListener);
                    } else {
                        dismissLoadingDialog();
                    }
                }
            }, 400);
        }

        @Override
        public void onConnectFailed(String error) {
            dismissLoadingDialog();
            Logger.i("bleinfo", "连接失败,关单");
            closeWorkOrder("2");
            ApiStore.bleRecord("2", orderId, carId, "connect");

        }

        @Override
        public void onConnectTimeoutEveryTime() {

        }
    };
    BluetoothHelper.OnOperateCarListener onOperateCarListener = new BluetoothHelper.OnOperateCarListener() {
        @Override
        public void onOperateSuccess(int[] status) {
            dismissLoadingDialog();
            closeWorkOrder("1");
            ApiStore.bleRecord("1", orderId, carId, "close");
        }

        @Override
        public void onOperateFailure(String error) {
            dismissLoadingDialog();
            closeWorkOrder("2");
            ApiStore.bleRecord("2", orderId, carId, "close");
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        Logger.i("returnCar-curposi", MyApplication.curPosition[0] + "==========" + MyApplication.curPosition[1]);
    }

    //对话框
    private void showOneButtonDialog(final String flag, String title, String message, String yestext) {
        final DialogOneButton dialogOneButton = new DialogOneButton(mContext);
        dialogOneButton.setTitle(title);
        dialogOneButton.setMessage(message);
        dialogOneButton.setCancelable(false);
        dialogOneButton.setCanceledOnTouchOutside(false);
        dialogOneButton.setYesOnclickListener(yestext, new DialogOneButton.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                if ("locationException".equals(flag)) {
                    AppManager.getAppManager().AppExit(mContext);
                } else if ("permission".equals(flag)) {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(intent);
                } else if ("locationfail".equals(flag)) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, Constants.REQUEST_LOCATION_SERVICE);
                }
                dialogOneButton.dismiss();
            }
        });
        dialogOneButton.show();

    }

    private void checkCanDropOffCar() {
        if ("1".equals(onGround)) {
            remarkMsg = remarkMsgUp;
            if (gridViewAddImgesAdpter.getCount() - 1 <= 0) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, "请先拍摄还车位置", ToastUtils.LENGTH_SHORT).show();
                return;
            }
        } else if ("0".equals(onGround)) {
            if (null != returnCarInParkName.getText() && null != returnCarInParkNum.getText()) {
                remarkMsg = returnCarInParkName.getText().toString() + return_car_in_park_ground.getText().toString() + returnCarInParkNum.getText().toString();
            }

            if (!CheckRegexUtils.checkParkName(returnCarInParkName.getText().toString())) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, "请填写停车场名称", ToastUtils.LENGTH_SHORT).show();
                return;
            } else if (TextUtils.isEmpty(returnCarInParkNum.getText().toString())) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, "请填写停车区号及车位编号", ToastUtils.LENGTH_SHORT).show();
                return;
            }
        } else {
            dismissLoadingDialog();
            ToastUtils.makeText(mContext, "请先选择还车位置", ToastUtils.LENGTH_SHORT).show();
            return;
        }
        //停车场收费选择
        if (!radioButtonFree.isChecked() && !radionButtonCharge.isChecked()) {
            dismissLoadingDialog();
            ToastUtils.makeText(mContext, "请选择停车场类型", ToastUtils.LENGTH_SHORT).show();
            return;
        }

        if ("1".equals(onGround)) {//地上
            List<String> success = new ArrayList<>();
            if (SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_NAME) != null) {
                success = Arrays.asList(SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_NAME).split(","));
            }
            File[] files = fileDir.listFiles();
            List<File> unUpdatePics = new ArrayList<>();
            if (files != null) {
                Arrays.sort(files);
                imgs = "";
                for (int i = 0; i < files.length; i++) {
                    if (files[i].getName().endsWith("jpg") && !success.contains(files[i].getName())) {
                        unUpdatePics.add(files[i]);
                    }
                }
            }

            if (unUpdatePics.size() != 0) {
                Observable
                        .fromIterable(unUpdatePics)
                        .flatMap(new Function<File, ObservableSource<UploadImageBaidu>>() {
                            @Override
                            public ObservableSource<UploadImageBaidu> apply(File file) throws Exception {
                                return Observable.create(new ObservableOnSubscribe<UploadImageBaidu>() {
                                    @Override
                                    public void subscribe(ObservableEmitter<UploadImageBaidu> emitter) throws Exception {
                                        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).uploadImageBaidu(((MyApplication) getApplication()).getRequestFieldMap(), "stsToken", "upload").enqueue(new Callback<UploadImageBaidu>() {
                                            @Override
                                            public void onResponse(Call<UploadImageBaidu> call, Response<UploadImageBaidu> response) {
                                                Logger.d("returnCar", "预备上传" + response.body().getAttachment().getBucketName());
                                                response.body().setFile(file);
                                                emitter.onNext(response.body());
                                                emitter.onComplete();
                                            }

                                            @Override
                                            public void onFailure(Call<UploadImageBaidu> call, Throwable t) {
                                                emitter.onComplete();
                                            }
                                        });
                                    }
                                });
                            }
                        })
                        .flatMap(new Function<UploadImageBaidu, ObservableSource<File>>() {
                            @Override
                            public ObservableSource<File> apply(UploadImageBaidu uploadImageBaidu) throws Exception {

                                return Observable.create(new ObservableOnSubscribe<File>() {
                                    @Override
                                    public void subscribe(ObservableEmitter<File> emitter) throws Exception {
                                        Logger.d("returnCar", "上传 开始" + uploadImageBaidu.getFile() + "   " + uploadImageBaidu.getAttachment().getBucketName());
                                        key = getFileNameNoExOrder(uploadImageBaidu.getFile());
                                        UploadPicUtil.getInstance().uploadPicToBos(
                                                uploadImageBaidu.getFile(),
                                                uploadImageBaidu.getAttachment().getAk(),
                                                uploadImageBaidu.getAttachment().getSk(),
                                                uploadImageBaidu.getAttachment().getBucketName(),
                                                uploadImageBaidu.getAttachment().getStsToken(),
                                                uploadImageBaidu.getAttachment().getBucketName(),
                                                key,
                                                new UploadPicUtil.OnFinishListener() {
                                                    @Override
                                                    public void onSuccess() {
                                                        SPUtils.getInstance(mContext).putStringValue(SPKey.RETURN_CAR_PIC_NAME, SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_NAME) + "," + uploadImageBaidu.getFile().getName());
                                                        emitter.onNext(uploadImageBaidu.getFile());
                                                        emitter.onComplete();
                                                        Logger.d("returnCar", "上传成功" + uploadImageBaidu.getFile().getName());
                                                    }

                                                    @Override
                                                    public void onFailure(String failReason) {
                                                        emitter.onComplete();
                                                        Logger.d("returnCar", "上传失败" + uploadImageBaidu.getFile().getName());
                                                    }
                                                });
                                    }
                                });
                            }
                        }).subscribe(new Observer<File>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(File file) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        for (int i = 0; i < files.length; i++) {
                            if (files[i].getName().endsWith("jpg") && files[i].getName().startsWith(orderId)) {
                                String name = getFileNameNoExOrder(files[i]);
                                imgs = imgs + name + ",";
                            }
                        }
                        dropOffCar();
                    }
                });
            } else {
                for (File file : files) {
                    if (file.getName().endsWith("jpg") && file.getName().startsWith(orderId)) {
                        String name = getFileNameNoExOrder(file);
                        imgs = imgs + name + ",";
                    }
                }
                dropOffCar();
            }

        } else {
            dropOffCar();
        }

    }

    //处理权限的回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startLocation();
            } else {
                new AlertDialog.Builder(mContext).setTitle("大道地服提示").setMessage("您拒绝了定位权限，无法关闭工单，请您到设置中开启权限。")
                        .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startAppSettings(mContext);
                            }
                        }).setCancelable(false).show();
            }
        }
    }

    //启动当前应用设置页面
    private static void startAppSettings(Context context) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        context.startActivity(intent);
    }

    private class CarTaskLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (!isReceiveLoc) {
                isReceiveLoc = true;
                if (bdLocation == null) {
                    dismissLoadingDialog();
                    showOneButtonDialog("locationException", "提醒", "定位异常，请退出应用再试。", "确定");
                    return;
                }
                int locationErrorCode = bdLocation.getLocType();
                if (locationErrorCode == BDLocation.TypeGpsLocation || locationErrorCode == TypeNetWorkLocation) {
                    //GPS或者网络定位成功
                    Logger.i("curPositionMain_cartask", "纬度" + bdLocation.getLatitude() + "经度" + bdLocation.getLongitude()
                            + "citycode" + bdLocation.getCityCode() + "countrycode" + bdLocation.getCountryCode());
                    bdLocation = LocationFilter.Algorithm(bdLocation);//根据历史定位，对定位的结果平滑过滤
                    LatLng curPosition;
                    if (!BuildConfig.DEBUG) {
                        curPosition = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());// 更新定位
                        ((MyApplication) getApplication()).setAreaCode(bdLocation.getCityCode());
                        ((MyApplication) getApplication()).setAdCode(bdLocation.getAdCode());
                        ((MyApplication) getApplication()).setCurPosition(curPosition.latitude + "", curPosition.longitude + "");
                    } else {
                        switch (SPUtils.getInstance(mContext).getIntValue(SPKey.LOCATIONMOED)) {
                            case 0:
                            case 1:
                                curPosition = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());// 更新定位
                                ((MyApplication) getApplication()).setAreaCode(bdLocation.getCityCode());
                                ((MyApplication) getApplication()).setAdCode(bdLocation.getAdCode());
                                ((MyApplication) getApplication()).setCurPosition(curPosition.latitude + "", curPosition.longitude + "");
                                break;
                            case 2:
                                curPosition = new LatLng(Double.parseDouble(SPUtils.getInstance(mContext).getStringValue(SPKey.FIX_LATITUDE)),
                                        Double.parseDouble(SPUtils.getInstance(mContext).getStringValue(SPKey.FIX_LONGITUDE)));// 更新定位
                                ((MyApplication) getApplication()).setAreaCode(SPUtils.getInstance(mContext).getStringValue(SPKey.AREA_CODE));
                                ((MyApplication) getApplication()).setAdCode(SPUtils.getInstance(mContext).getStringValue(SPKey.AD_CODE));
                                ((MyApplication) getApplication()).setCurPosition(SPUtils.getInstance(mContext).getStringValue(SPKey.FIX_LATITUDE),
                                        SPUtils.getInstance(mContext).getStringValue(SPKey.FIX_LONGITUDE));
                                break;
                        }
                    }
                    checkCanDropOffCar();
                } else {//定位失败
                    Logger.i("loctionerror_cartask", bdLocation.getLocType() + "");
                    dismissLoadingDialog();
                    if (locationErrorCode == TypeServerError) {  //缺少定位权限
                        showOneButtonDialog("permission", "提醒", "您可能拒绝了定位权限，请在设置中开启权限。", "去设置");
                    } else {
                        DialogTwoButton inCarDialog = new DialogTwoButton(CarTaskActivity.this);
                        inCarDialog.setTitle("提醒");
                        inCarDialog.setMessage("您需要开启定位服务");
                        inCarDialog.setYesOnclickListener("开启", () -> {
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, Constants.REQUEST_LOCATION_SERVICE);
                            inCarDialog.dismiss();
                        });
                        inCarDialog.setNoOnclickListener("取消", () -> inCarDialog.dismiss());
                        inCarDialog.setCanceledOnTouchOutside(true);
                        inCarDialog.setCancelable(true);
                        inCarDialog.show();
                    }
                }
            }
        }
    }
}

